<?php
/**
 * Created by PhpStorm.
 * User: Steven
 * Date: 2017/7/6
 */

namespace app\order\controller;


use app\classes\model\ClassModel;
use app\financial\model\OrderModel;
use app\student\model\StudentModel;
use cmf\controller\UserBaseController;
use think\Db;
use think\Exception;
use think\Log;

class FrontOrderController extends UserBaseController
{
    public function index()
    {
        $limit = config('limit_front_per_page');
        $order_status = -1;//全部
        $where['o.shop_id'] = ['=', $this->front_shop_id];

        //当前家长
        $cur_uid = cmf_get_current_user_id();
        //获取家长的孩子
        $student_mdl = new StudentModel();
        $students = $student_mdl->getStudentsByPid($cur_uid, $this->front_shop_id);
        if (!$students) {
            $this->redirect('order/Order/add_student');
        }

        if (isset($_SESSION['student_id']) && !empty($_SESSION['student_id'])) {
            $student_id = $_SESSION['student_id'];
        } else {
            //设置当前学生
            $_SESSION['student_id'] = $students[0]['id'];
            //默认第一个孩子
            $student_id = $students[0]['id'];
        }
        //该家长下孩子的所有订单
        $where['o.parent_id'] = ['=', $cur_uid];

        $param = $this->request->param();

        //订单类型(0待支付，1已支付，2已完成，3已取消，4已退课)
        if (isset($param['status']) && is_numeric($param['status'])) {
            switch (intval($param['status'])) {
                case 0:
                    $order_status = 0;
                    break;
                case 1:
                    $order_status = 1;
                    break;
                case 2:
                    $order_status = 2;
                    break;
                case 3:
                    $order_status = 3;
                    break;
                case 4:
                    $order_status = 4;
                    break;
                default:
                    $order_status = -1;
                    break;
            }
            if ($order_status != -1) {
                $where['o.order_status'] = ['=', $order_status];
            }
        }

        //排序
        $sort = ['o.order_status' => 'asc'];

        //获取订单
        $order_mdl = new OrderModel();
        $data = $order_mdl->getOrder($where, $sort, $limit, []);

        $this->assign('students', $students);
        $this->assign('order_status', $order_status);
        $this->assign('order', $data);
        $this->assign('page', $data->render());

        return $this->fetch();
    }

    /**
     * 申请退课
     * @return mixed
     */
    public function refund()
    {
        return $this->fetch();
    }

    /**
     * 请求支付
     * @return mixed
     */
    public function orderPay()
    {
        $param = $this->request->param();
        if (!isset($_SESSION['student_id']) || empty($_SESSION['student_id'])) {
            //跳转到订单首页
            $this->redirect('order/FrontOrder/index');
        }
        $student_id = $_SESSION['student_id'];

        if (!isset($param['order_id']) || empty($param['order_id'])) {
            $this->error('订单编号不能为空');
        }

        $order_id = base64_decode($param['order_id']);
        $where = [
            'o.order_id' => ['=', $order_id],
            'o.student_id' => ['=', $student_id],
        ];
        $order_mdl = new OrderModel();
        $order = $order_mdl->getOrderByField($where);
        if (count($order) <= 0) {
            $this->error('该订单不存在');
        }
        //取消订单截止时间
        $cancel_time = $order['cancel_time'];
        //剩余时间
        $left_time = $cancel_time - time();

        $hour = floor($left_time / 3600);
        $minute = floor(($left_time % 3600) / 60);
        $second = $left_time - $hour * 3600 - $minute * 60;
        if ($hour < 10) {
            $hour = '0' . $hour;
        }
        if ($minute < 10) {
            $minute = '0' . $minute;
        }
        if ($second < 10) {
            $second = '0' . $second;
        }


        $this->assign('order', $order);
        $this->assign('left_time', $left_time);
        $this->assign('hour', $hour);
        $this->assign('minute', $minute);
        $this->assign('second', $second);

        return $this->fetch();
    }

    /**
     * 根据支付方式请求支付
     * @return \think\response\Json
     */
    public function ajax_pay()
    {
        $param = $this->request->post();
        if (!isset($param['order_id']) || empty($param['order_id'])) {
            $json_data = [
                'code' => 0,
                'msg' => '订单号不能为空',
                'data' => []
            ];
            return json($json_data);
        }
        if (!isset($param['pay_type']) || empty($param['pay_type'])) {
            $json_data = array(
                'code' => 0,
                'msg' => '支付方式不能为空',
                'data' => array()
            );
            return json($json_data);
        }

        if (!isset($_SESSION['student_id']) || empty($_SESSION['student_id'])) {
            //跳转到家校通首页
            $this->redirect('order/FrontOrder/index');
        }
        $student_id = $_SESSION['student_id'];
        $order_id = base64_decode($param['order_id']);
        $pay_type = $param['pay_type'];//支付方式
        switch ($pay_type) {
            case 'alipay':
                $pay_url = url('pay/Alipay/doAlipay', ['order_id' => base64_encode($order_id)]);
                break;
            case 'wxpay':
                $pay_url = url('pay/Wxpay/index', ['order_id' => base64_encode($order_id)]);
                break;
            default:
                $pay_url = url('pay/Alipay/doAlipay', ['order_id' => base64_encode($order_id)]);
                break;
        }

        $json_data = [
            'code' => 1,
            'msg' => 'success',
            'data' => $pay_url
        ];
        return json($json_data);
    }

    /**
     * 取消过期订单
     * @return \think\response\Json
     */
    public function ajax_cancel()
    {
        $param = $this->request->post();
        if (!isset($param['order_id']) || empty($param['order_id'])) {
            $json_data = [
                'code' => 0,
                'msg' => '订单号不能为空',
                'data' => []
            ];
            return json($json_data);
        }

        if (!isset($_SESSION['student_id']) || empty($_SESSION['student_id'])) {
            //跳转到家校通首页
            $this->redirect('order/FrontOrder/index');
        }
        $student_id = $_SESSION['student_id'];
        $order_id = base64_decode($param['order_id']);

        $where = [
            'order_id' => ['=', $order_id],
        ];
        //获取订单
        $order_mdl = new OrderModel();
        $order = $order_mdl->where($where)->find();
        if (count($order) <= 0) {
            $json_data = [
                'code' => 0,
                'msg' => '该订单不存在',
                'data' => []
            ];
            return json($json_data);
        }

        if ($order['cancel_time'] < time()) {
            //订单已过期，修改订单状态,同时释放座位，优惠返回等相关操作
            $update_data = [
                'id' => $order['id'],
                'order_status' => 3,//已取消
                'update_time' => time(),
            ];
            //修改订单
            $order_mdl->editOrder($update_data);

            //释放座位
            $class_mdl = new ClassModel();
            $class_mdl->releaseSeat($order['class_id'], $order['student_id'], $this->front_shop_id);

            //释放优惠
            $award_where = [
                'student_id' => $order['student_id'],
                'order_id' => $order['id'],
            ];
            $seat = Db::name('award_order')->where($award_where)->find();
            if (count($seat) > 0) {
                Db::name('award_order')->where($award_where)->delete();
            }
        } else {
            $json_data = [
                'code' => 0,
                'msg' => '该订单没有过期',
                'data' => []
            ];
            return json($json_data);
        }

        $json_data = [
            'code' => 1,
            'msg' => 'success',
            'data' => url('order/FrontOrder/index')
        ];
        return json($json_data);
    }


    /**
     * 手动取消订单
     * @return \think\response\Json
     */
    public function cancel()
    {
        $param = $this->request->param();
        if (!isset($param['order_id']) || empty($param['order_id'])) {
            $this->error('订单号不能为空', 'order/FrontOrder/index');
        }

        if (!isset($_SESSION['student_id']) || empty($_SESSION['student_id'])) {
            //跳转到家校通首页
            $this->error('没有选择学员', 'order/FrontOrder/index');
        }
        $student_id = $_SESSION['student_id'];
        $order_id = base64_decode($param['order_id']);

        $where = [
            'order_id' => ['=', $order_id],
            'student_id' => ['=', $student_id],
        ];

        //获取订单
        $order_mdl = new OrderModel();
        $order = $order_mdl->where($where)->find();
        if (count($order) <= 0) {
            $this->error('当前学员没有该订单', 'order/FrontOrder/index');
        }

        //订单已过期，修改订单状态,同时释放座位，优惠返回等相关操作
        $update_data = [
            'id' => $order['id'],
            'order_status' => 3,//已取消
            'update_time' => time(),
        ];
        //修改订单
        $order_mdl->editOrder($update_data);

        //释放座位
        $class_mdl = new ClassModel();
        $class_mdl->releaseSeat($order['class_id'], $order['student_id'], $this->front_shop_id);

        //释放优惠
        $award_where = [
            'student_id' => $order['student_id'],
            'order_id' => $order['id'],
        ];
        $seat = Db::name('award_order')->where($award_where)->find();
        if (count($seat) > 0) {
            Db::name('award_order')->where($award_where)->delete();
        }

        $this->success('订单取消成功');
    }

}